import { Reducer, Action } from './model/redux.model';

const reducer1: Reducer<number> = (state: number, action: Action) => {
    return state;
};
console.log(reducer1(0, null));

// 修改state中的数据
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const reducer2: Reducer<number> = (state: number, action: Action) => {
    if (action.type === INCREMENT) {
        return state + 1;
    }
    if (action.type === DECREMENT) {
        return state - 1;
    }
}

const action1: Action = { type: 'INCREMENT' };
const action2: Action = { type: 'DECREMENT' };

console.log(reducer2(0, action1));
console.log(reducer2(0, action2));

// reducer的switch版本
const reducer3: Reducer<number> = (state: number, action: Action) => {
    switch (action.type) {
        case INCREMENT:
            return state + 1;
        case DECREMENT:
            return state - 1;
        default:
            return state;
    }
}

console.log(reducer3(100, action1));
console.log(reducer3(100, action2));

// 应用的变化通常无法通过单一变量来反映，所以需要借助action中的第二个参数payload来做补充
const reducer4: Reducer<number> = (state: number, action: Action) => {
    switch (action.type) {
        case INCREMENT:
            return state + action.payload;
        case DECREMENT:
            return state - action.payload;
        default:
            return state;
    }
}

// 借助Action中的payload字段来补充increment/decrement中的“步长”
const action3: Action = {type: 'INCREMENT', payload: 100};
const action4: Action = {type: 'DECREMENT', payload: 100};

console.log(reducer4(0, action3));
console.log(reducer4(0, action4));